import argparse
import os


def walk_check(dir, key):
    src_path = os.getcwd()
    try:
        os.chdir(dir)
    except:
        print('invalid dir')
    lines = 0
    for path, dirs, files in os.walk('.'):
        for rel_name in files:
            if rel_name.split('.')[-1] not in ['c', 'cc', 'cpp', 'h', 'hpp']:
                continue
            abs_name = os.path.join(path, rel_name)
            with open(abs_name, encoding='utf-8') as fp:
                contains = []
                for i, line in enumerate(fp):
                    lines += 1
                    if key in line:
                        contains.append(i + 1)
                if len(contains) == 0:
                    continue
                print(f'`{key}` found in  {os.path.relpath(abs_name, src_path):24s}:  [line {str(contains).strip("[]")}]')
    print(f'\n[num lines of src{f"/{dir}" if dir != "." else ""}: {lines}]')


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--dir', required=True, type=str)
    parser.add_argument('--key', required=True, type=str)
    args = parser.parse_args()
    walk_check(args.dir, args.key)


if __name__ == '__main__':
    main()
